package com.zhe.zheblogmaster.handler.blog;

import com.github.pagehelper.PageInfo;
import com.zhe.zheblogmaster.config.BlogConstants;
import com.zhe.zheblogmaster.entity.BlogCategory;
import com.zhe.zheblogmaster.entity.BlogComment;
import com.zhe.zheblogmaster.entity.Link;
import com.zhe.zheblogmaster.entity.vo.BlogDetailVO;
import com.zhe.zheblogmaster.entity.vo.BlogVO;
import com.zhe.zheblogmaster.entity.vo.SimpleBlogVO;
import com.zhe.zheblogmaster.service.*;
import com.zhe.zheblogmaster.util.PatternUtil;
import com.zhe.zheblogmaster.util.ResultBody;
import com.zhe.zheblogmaster.util.ZheBlogUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author WHAOU
 * @date 2021/8/22
 * @email whaou@qq.com
 */
@Controller
public class ReadBlogHandler {
    private static final String THEME = "blog/luna/";
    @Autowired
    private BlogService blogService;
    @Autowired
    private ConfigService configService;
    @Autowired
    private BlogCategoryService categoryService;
    @Autowired
    private LinkService linkService;
    @Autowired
    private BlogCommentService commentService;

    @PostMapping("/blog/comment")
    @ResponseBody
    public ResultBody<String> getComment(HttpServletRequest request, HttpSession session,
                                         @RequestParam Long blogId, @RequestParam String verifyCode,
                                         @RequestParam String commentator, @RequestParam String email,
                                         @RequestParam String websiteUrl, @RequestParam String commentBody) {
        if (verifyCode == null || "".equals(verifyCode)) {
            return ResultBody.error("验证码不能为空");
        }
        String captcha = String.valueOf(session.getAttribute(BlogConstants.VERIFY_CODE));
        if (captcha == null || "".equals(captcha)) {
            return ResultBody.error("非法请求");
        }
        if (!verifyCode.equals(captcha)) {
            return ResultBody.error("验证码错误");
        }
        String ref = request.getHeader("Referer");
        if (ref == null || "".equals(ref)) {
            return ResultBody.error("非法请求");
        }
        if (blogId == null || blogId < 0) {
            return ResultBody.error("非法博客id");
        }
        if (commentator == null || "".equals(commentator)) {
            return ResultBody.error("请输入称呼");
        }
        if (email == null || "".equals(email)) {
            return ResultBody.error("请输入邮箱地址");
        }
        if (!PatternUtil.isEmail(email)) {
            return ResultBody.error("请输入正确的邮箱地址");
        }
        if (commentBody == null || "".equals(commentBody)) {
            return ResultBody.error("请输入评论内容");
        }
        if (commentBody.trim().length() > 200) {
            return ResultBody.error("评论内容过长");
        }
        BlogComment comment = new BlogComment();
        comment.setBlogId(blogId);
        comment.setCommentator(ZheBlogUtils.cleanString(commentator));
        comment.setEmail(email);
        if (PatternUtil.isURL(websiteUrl)) {
            comment.setWebsiteUrl(websiteUrl);
        }

        LocalDateTime localDateTime = LocalDateTime.now();
        Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
        comment.setCommentCreateTime(date);
        comment.setCommentBody(ZheBlogUtils.cleanString(commentBody));
        Boolean res = commentService.addComment(comment);
        return ResultBody.successWithData(String.valueOf(res));
    }


    @GetMapping("/blog/{blogId}")
    public String getBlog(@PathVariable("blogId") Long blogId,
                          @RequestParam(value = "commentPage", required = false, defaultValue = "1") Integer pageNum,
                          Model model) {
        BlogDetailVO blogDetailVO = blogService.getBlogDetailVOById(blogId);
        if (blogDetailVO != null) {
            model.addAttribute("blogDetailVO", blogDetailVO);
            PageInfo<BlogComment> commentPageInfo = commentService.getCommentPageByBlogId(blogId, pageNum);
            model.addAttribute("commentPageResult", commentPageInfo);
        }
        model.addAttribute(BlogConstants.TITLE, "详情");
        model.addAttribute(BlogConstants.CONFIGURATIONS, configService.getAllConfig());
        return THEME + "detail";
    }

    /**
     * 导航条 link
     *
     * @return 返回友链页
     */
    @GetMapping("/link")
    public String getLinkPage(Model model) {
        // 设置页面标题 <title></title>
        model.addAttribute(BlogConstants.TITLE, "友情链接");
        // 获取所有友链并分类
        Map<Byte, List<Link>> linkMap = linkService.getLinks();
        if (linkMap != null) {
            // 判读友链类别，分别传递至页面 0-友链 1-推荐 2-个人网站
            if (linkMap.containsKey((byte) 0)) {
                model.addAttribute("favoriteLinks", linkMap.get((byte) 0));
            }
            if (linkMap.containsKey((byte) 1)) {
                model.addAttribute("recommendLinks", linkMap.get((byte) 1));
            }
            if (linkMap.containsKey((byte) 2)) {
                model.addAttribute("personalLinks", linkMap.get((byte) 2));
            }
        }
        model.addAttribute(BlogConstants.CONFIGURATIONS, configService.getAllConfig());
        return THEME + "link";
    }

    /**
     * 导航条分类
     */
    @GetMapping("/categories")
    public String getCategories(Model model) {
        List<BlogCategory> categoryList = categoryService.getAll();
        model.addAttribute(BlogConstants.CATEGORIES, categoryList);
        model.addAttribute(BlogConstants.TITLE, "分类");
        model.addAttribute(BlogConstants.CONFIGURATIONS, configService.getAllConfig());
        return THEME + "category";
    }

    @GetMapping("/category/{categoryName}")
    public String category(@PathVariable("categoryName") String categoryName, Model model) {
        return category(categoryName, model, 1);
    }

    @GetMapping("/category/{categoryName}/{pageNum}")
    public String category(@PathVariable("categoryName") String categoryName, Model model, @PathVariable("pageNum") Integer pageNum) {
        PageInfo<SimpleBlogVO> pageInfo = blogService.getSimpleBlogVOByCategoryName(categoryName, pageNum);
        model.addAttribute(BlogConstants.BLOG_PAGE_RESULT, pageInfo);
        model.addAttribute(BlogConstants.TITLE, "分类");
        model.addAttribute(BlogConstants.KEYWORD, categoryName);
        model.addAttribute(BlogConstants.CONFIGURATIONS, configService.getAllConfig());
        model.addAttribute("prefix", "category/");
        return THEME + "search-page";
    }

    /**
     * 首页
     */
    @GetMapping({"/", "/index", "/index.html"})
    public String index(Model model) {
        return page(1, model);
    }

    /**
     * 博客列表
     */
    @GetMapping({"/page/{pageNum}", "/page/{pageNum}.html"})
    public String page(@PathVariable("pageNum") Integer pageNum, Model model) {
        // 获取第pageNum页的博客信息
        PageInfo<BlogVO> pageInfo = blogService.getBlogVOList(pageNum);
        // 将获取到的博客存入model，以便前端读取
        model.addAttribute(BlogConstants.BLOG_PAGE_RESULT, pageInfo);
        // 设置页面标题
        model.addAttribute(BlogConstants.TITLE, "首页");
        // 获取本站的所有自定义配置信息，并存入model
        Map<String, String> allConfig = configService.getAllConfig();
        model.addAttribute(BlogConstants.CONFIGURATIONS, allConfig);
        // 获取最新发布博客列表，并存入model
        List<SimpleBlogVO> newBlogList = blogService.getLatestBlogRecords(BlogConstants.LIMIT);
        model.addAttribute(BlogConstants.LATEST_BLOG_RECORDS, newBlogList);
        // 获取点击最多的博客列表
        List<SimpleBlogVO> hotBlogs = blogService.getHotBlogs(BlogConstants.LIMIT);
        model.addAttribute(BlogConstants.HOT_BLOGS, hotBlogs);
        return THEME + "index";
    }

    /**
     * 搜索功能
     *
     * @param keyword 关键词
     */
    @GetMapping("/search/{keyword}")
    public String search(@PathVariable("keyword") String keyword, Model model) {
        return search(keyword, 1, model);
    }

    @GetMapping("/search/{keyword}/{pageNum}")
    public String search(@PathVariable("keyword") String keyword,
                         @PathVariable("pageNum") Integer pageNum,
                         Model model) {
        // 根据关键字查询博客记录并存入model
        PageInfo<SimpleBlogVO> pageInfo = blogService.getBlogVOListByKeyword(keyword, pageNum);
        model.addAttribute(BlogConstants.BLOG_PAGE_RESULT, pageInfo);
        model.addAttribute(BlogConstants.TITLE, "搜索");
        model.addAttribute(BlogConstants.KEYWORD, keyword);
        Map<String, String> allConfig = configService.getAllConfig();
        model.addAttribute(BlogConstants.CONFIGURATIONS, allConfig);
        model.addAttribute("prefix", "search/");
        return THEME + "search-page";
    }


    @GetMapping({"/about"})
    public String about(Model model) {
        BlogDetailVO blogDetailVO = blogService.getAboutBlog();
        if (blogDetailVO == null) {
            return "error/404";
        }
        model.addAttribute(BlogConstants.BLOG_DETAIL_VO, blogDetailVO);
        model.addAttribute(BlogConstants.TITLE, "关于");
        model.addAttribute(BlogConstants.CONFIGURATIONS, configService.getAllConfig());
        return THEME + "about";
    }
}
